#include "allheaders.hpp"

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    std::map<std::string, napi_ref *> *refMap = nullptr;
    napi_get_instance_data(env, (void**)&refMap);
    if (refMap == nullptr) {
        refMap = new std::map<std::string, napi_ref *>;
    }
    napi_set_instance_data(env, refMap, [](napi_env env, void *data, void *hint){
        LOGINFO("hmz exit, start clean resource!");
        std::map<std::string, napi_ref *> *mp = reinterpret_cast<std::map<std::string, napi_ref *> *>(data);
        for (auto itr = mp->begin(); itr != mp->end(); itr++) {
            uint32_t count = 0;
            napi_reference_unref(env, *(itr->second), &count);
            napi_delete_reference(env, *(itr->second));
            delete (itr->second);
            itr->second = nullptr;
        }
        delete mp;
        mp = nullptr;
    }, nullptr);
    
    demo_function::Exports(env, exports);
    demo_class::person::Exports(env, exports);
    demo_call_js_function::Exports(env, exports);
    demo_async_function::Exports(env, exports);
    
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "entry",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
    napi_module_register(&demoModule);
}
